package com.java.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: wjr
 * @Description: 拦截器
 * @Date Created in  2020-09-04 1:30
 * @Modified By:
 */
public class HttpFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //对所有servlet请求设置编码集
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding("utf-8");

        String requestURI = request.getRequestURI();
        String username = (String) request.getSession().getAttribute("username");
        //为登录时，对某些请求放行
        if (requestURI.endsWith("/") || requestURI.endsWith("/index.jsp")
                || requestURI.endsWith("/login") || username != null){
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            //如果处于未登录状态，提示登录并跳转到登录界面
            response.setContentType("text/html;charset=utf-8");
            PrintWriter printWriter = response.getWriter();
            printWriter.print("<script>alert('请先登录！');location.href='/index.jsp'</script>");
        }
    }

    @Override
    public void destroy() {

    }
}
